<template>
  <div class="chart-container">
    <el-card>
      <div class="chart-wrapper">
        <el-empty v-if="faultData.length === 0" description="No data available" />
        <div v-else ref="chartRef" style="height: 500px;"></div>
      </div>
    </el-card>
  </div>

  
</template>

<script setup>
  import { ref,onMounted, watch, nextTick,computed } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts';
  import { useManageStore } from '../../store/manageStore';
  import { useLoading } from '../../utils/loading';
  import { useSidebarStore } from '../../store/sidebarStore';
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL

  const faultData = ref([])
  const chartRef = ref(null)
  let chartInstance = null
  const sidebarStore = useSidebarStore();
  const manageStore = useManageStore()
  const isCollapse = computed(() => sidebarStore.isCollapse);
  const dealer = computed(() => manageStore.dealer)
  watch(isCollapse,async(newVal) => {
    await getFault();
  },{ flush: 'post' }) 
  onMounted(() => {
    getFault()
  })

  const getFault = async() => {
    showLoading('loading...')
    try{
      const res = await axios.get(`${BASE_URL}manage/countFaultPart`,{
        params:{
          dealer:dealer.value
        }
      })
      if(res.data && res.data.data) {
        faultData.value = res.data.data.map(item => ({
          name:item.title,
          value:item.num
        }))
      }
    }catch(error){
      ElMessage.error('Failed to obtain fault data');
    }finally{
      hideLoading();
    }
  }
  
  // 监听数据变化并渲染图表
  watch(faultData,(newVal) => {
    if(newVal.length > 0) {
      nextTick(() => {
        initChart()
      })
    }
  },{ deep:true })

  const initChart = () => {
    if(!chartRef.value) return

    //销毁之前的图表实例
    if(chartInstance) {
      chartInstance.dispose();
    }

    //初始化新表图
    chartInstance = echarts.init(chartRef.value)

    const option = {
      title: {
        text: 'Distribution of Faulty Components',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: '10%',
        data: faultData.value.map(item => item.name)
      },
      series: [{
        name: 'Number of failures',
        type: 'pie',
        center: ['60%', '55%'],
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: faultData.value
      }]
    }
    chartInstance.setOption(option);
  
    // 响应式调整
    window.addEventListener('resize', function() {
      chartInstance.resize();
    });
  }

</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
}
.chart-wrapper {
  width: 100%;
  height: 100%;
}
</style>